<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter.js';
import { ElMessage } from 'element-plus'
const counter = useCounterStore();
const menu = ref([]);
const router = useRouter();

function showView() {
    const data = counter.menu.filter(f => f.isSave == true).map(m => {
        return {
            ...m,
            path: '/detail' + m.path
        }
    })
    if (data.length == 0) {
        return ElMessage.warning('请先保存问卷！')
    }
    counter.updateQuestion(data)
    router.push('/detail')
}

function addTitle() {
    if (counter.menu.length > 10) {
        ElMessage({
            message: '目前只允许增加十道题',
            type: 'warning',
        })
        return
    }
    counter.addMenu()
}


watch(() => counter.menu, (newVal) => {
    if (newVal) {
        menu.value = newVal
    }
}, {
    immediate: true,
    deep: true
})

onMounted(() => {
    menu.value = counter.menu;
})
</script>

<template>
    <section>
        <el-container>
            <el-aside width="300px" class="menu">
                <div class="view">
                    <el-button @click="showView">
                        <el-icon>
                            <View style="cursor: pointer;" />
                        </el-icon>
                        预览
                    </el-button>
                    <el-button type="primary" @click="addTitle">
                        <el-icon>
                            <Plus style="cursor: pointer;" />
                        </el-icon>
                        新增题目
                    </el-button>
                </div>
                <el-menu router :unique-opened="true">
                    <el-menu-item v-for="item in menu" :key="item.path" :index="item.path">{{
                        item.name }}<el-tag type="success" v-if="item.isSave">已保存</el-tag></el-menu-item>
                </el-menu>

            </el-aside>
            <el-main>
                <router-view />
            </el-main>
        </el-container>
    </section>
</template>

<style scoped lang="scss">
.menu {
    border: 1px solid #eee;
    // border-right: 1px solid #eee;
    height: 80vh;
}

.view {
    padding: 10px 20px;
}
</style>
